package com.zxcz.controller;

import java.util.HashMap;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.zxcz.domain.Resource;
import com.zxcz.domain.Result;
import com.zxcz.service.OssService;
import com.zxcz.service.ResourceService;
import com.zxcz.tools.CustomHttpStatus;
import com.zxcz.tools.ResultUtil;

/**
 * oss相关操作接口
 */
@Controller
@Transactional //开启事务
@RequestMapping(value = "/aliyun/oss")
public class OssController {
	@Autowired
	private OssService ossService;
	@Autowired
	private ResourceService resourceService;
	private static final Log logger = LogFactory.getLog(OssController.class);
	
	/**
	 * 上传资源
	 * @param resource
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/policy")
	public Result<Object> policy(Resource resource) {
		//oss
		Result<Object> result = ossService.policy(resource.getName());
		HashMap<String, Object> data = (HashMap<String, Object>) result.getData();
		String objectName = (String) data.get("objectName");
		resource.setOssObject(objectName);
		
		logger.info("objectName -->" + objectName);
		
		//数据库查询是否存在
		Resource re = resourceService.findResourceByOssObject(resource.getOssObject());
		if(re == null) {
			data.put("resource", resource);
			result.setData(data);
			return result;
		}else {
			logger.warn("OSS已经存在" + re.getOssObject()+"文件");
			return ResultUtil.generate(CustomHttpStatus.FILE_EXISTS.getValue(), "OSS已经存在"+re.getOssObject()+"文件");
		}
		
	}
	
	/**
	 * 删除资源
	 * @param id
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/delete")
	public Result<Object> delete(int id) {
		Resource resource = resourceService.findResourceById(id);
		//删除数据库上的数据
		resourceService.deleteResource(id);
		//删除oss的资源
		return ossService.deleteResource(resource);
	}
	
	/**
	 * 更新资源
	 * @param resource
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/update")
	public Result<Object> update(Resource resource) {
		Resource re = resourceService.findResourceById(resource.getId());
		//更新资源文件时不更改原文件名字
		Result<Object> result = ossService.policy(re.getName());
		HashMap<String, Object> data = (HashMap<String, Object>) result.getData();
		data.put("resource", re);
		result.setData(data);
		return result;
	}

}	
